﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using WindowsFormsApp1.IICMoudle;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static WindowsFormsApp1.IICMoudle.I2CProxy;
using static WindowsFormsApp1.IICMoudle.Utils;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {

        private bool isOpen = false;   // 设备是否已打开
        private string fwVersion = ""; // 固件版本号
        private bool isPolling = false;//数据轮询
        private string moudleConnect = "111111";//模组通断
        public static I2CProxy i2c = I2CProxy.GetInstace((int)ChipType.CHIP_SEA);
        // 数据存储
        private List<double> xData = new List<double>();
        private List<double> yData = new List<double>();
        // 你的文本文件路径（替换为实际路径）
        private string filePath = @"D:\Visual Studio Test\WindowsFormsApp1\Data";

        public Form1()
        {
            InitializeComponent();
            i2c.Open();
            InitChart();
            // 窗口设置
            this.Text = "原生绘图示例";
            this.Size = new Size(800, 600);

            //设备连接状态判断与IO初始化
            if (i2c.Open() && IOoperation.IOInit())
            {
                isOpen = true;
                label_conn_status.Text = "Device Connect!";
                label_conn_status.ForeColor = Color.Green;
            }
            else
            {
                isOpen = false;
                label_conn_status.Text = "Decive Not Found!";
                label_conn_status.ForeColor = Color.Red;
            }

        }

        private void fwVersion_label_Click(object sender, EventArgs e)
        {
        }
       
        private void button1_Click(object sender, EventArgs e)
        {
            //读取固件版本号

            //fwVersion = i2c.ReadFwVersion();
            //tvFwVersion.Text = fwVersion;

            //读取校准系数

            //string coefStr = coef_textBox_addr.Text;
            //if (coefStr.Trim().Equals(string.Empty) || !StringTool.IsHex(coefStr))
            //{
            //    return;
            //}
            //string coefLenStr = coef_textBox_Len.Text;
            //if (coefLenStr.Trim().Equals(string.Empty) || !int.TryParse(coefLenStr, out int iLength))
            //{
            //    return;
            //}
            //byte[] coefData = StringTool.StrToToHexByte(coefStr);
            //int rLen = int.Parse(coefLenStr);
            //byte[] coefRs = i2c.ReadReg(coefData, rLen);
            //string[] coefRsStr = Utils.DecToHex(coefRs);


            // 直接处理每个拼接后的结果
            // int[] values = HexDataProcessor.ProcessHexArray(coefRsStr);

            // 存储每个结果除以1000后的字符串
            //List<string> resultList = new List<string>();
            //foreach (int val in values)
            //{
            //    //    // 每个结果除以1000并保留3位小数
            //    double singleResult = Math.Round(val / 1000.0, 3);
            //    resultList.Add(singleResult.ToString());
            //}
            //coef_textbox.Text = string.Join(", ", resultList);

            //读取offset
            //读取DAC转换系数


            //string DecStr = textBox1.Text;
            //byte[] DecData = StringTool.StrToToHexByte(DecStr);
            //string DecLenStr = textBox2.Text;
            //int rLen1 = int.Parse(DecLenStr);
            //byte[] DecRs = i2c.ReadReg(DecData, rLen1);
            //string[] DecRsStr = Utils.DecToHex(DecRs);
            //int dacToMv = DecRs[1] << 8 | DecRs[0];
            //double dacToMvre = Math.Round(dacToMv / 1000.0, 3);
            //Console.WriteLine(dacToMvre);

            //string OffStr = textBox3.Text;
            //byte[] OffData = StringTool.StrToToHexByte(OffStr);
            //string OffLenStr = textBox4.Text;
            //int rLen2 = int.Parse(OffLenStr);
            //byte[] OffRs = i2c.ReadReg(OffData, rLen2);
            //string[] OffRsStr = Utils.DecToHex(OffRs);
            //int[] result = HexDataProcessor.ProcessHexArray(OffRsStr);

            // 定义数组存储相乘结果
            // double[] multipliedResults = new double[result.Length];

            // 逐个元素相乘：当前result的每个值 × 前面的resultValues对应的值

            //    for (int i = 0; i < result.Length; i++)
            //    {
            //        multipliedResults[i] = result[i] * dacToMvre;

            //    }
            //    // Console.WriteLine(multipliedResults.ToString());
            //    string str = string.Join(" ", multipliedResults);
            //    offset_textBox.Text = str;

        }


        //检查是否处于轮询状态并读取模块连接状态并显示
        private void label9_Click(object sender, EventArgs e)
        {

        }
        private void textBox_rLen1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_write1_Click(object sender, EventArgs e)
        {
            string writeStr = textBox_write1.Text;
            if (writeStr.Trim().Equals(string.Empty) || !StringTool.IsHex(writeStr))
            {
                richTextBox_info.AppendText("write data error\r\n");
                return;
            }
            byte[] writedata = StringTool.StrToToHexByte(writeStr);
            int writeLen = writedata.Length;
            if (i2c.WriteReg(writedata, writeLen))
            {
                richTextBox_info.AppendText("Write Succes\r\n");
            }
            else
            {
                richTextBox_info.AppendText("Write Failed\r\n");
            }
        }

        private void textBox_write2_TextChanged(object sender, EventArgs e)
        {
        }

        private void textBox_write3_TextChanged(object sender, EventArgs e)
        {
        }

        private void btn_write2_Click(object sender, EventArgs e)
        {
            string writeStr = textBox_write2.Text;
            if (writeStr.Trim().Equals(string.Empty) || !StringTool.IsHex(writeStr))
            {
                richTextBox_info.AppendText("write data error\r\n");
                return;
            }
            byte[] writeData = StringTool.StrToToHexByte(writeStr);
            int writeLen = writeData.Length;
            if (i2c.WriteReg(writeData, writeLen))
            {
                richTextBox_info.AppendText("write succes\r\n");
            }
            else
            {
                richTextBox_info.AppendText("write fail\r\n");
            }
        }

        private void btn_write3_Click(object sender, EventArgs e)
        {
            string writeStr = textBox_write3.Text;
            if (writeStr.Trim().Equals(string.Empty) || !StringTool.IsHex(writeStr))
            {
                richTextBox_info.AppendText("write data error\r\n");
                return;
            }
            byte[] writeData = StringTool.StrToToHexByte(writeStr);
            int writeLen = writeData.Length;
            if (i2c.WriteReg(writeData, writeLen))
            {
                richTextBox_info.AppendText("write succes\r\n");
            }
            else
            {
                richTextBox_info.AppendText("write fail\r\n");
            }
        }

        private void btn_write4_Click(object sender, EventArgs e)
        {
            string writeStr = textBox_write4.Text;
            if (writeStr.Trim().Equals(string.Empty) || !StringTool.IsHex(writeStr))
            {
                richTextBox_info.AppendText("write data error\r\n");
                return;
            }
            byte[] writeData = StringTool.StrToToHexByte(writeStr);
            int writeLen = writeData.Length;
            if (i2c.WriteReg(writeData, writeLen))
            {
                richTextBox_info.AppendText("write success\r\n");
            }
        }
        private void btn_read1_Click(object sender, EventArgs e)
        {
            string readStr = textBox_read1.Text;
            if (readStr.Trim().Equals(string.Empty) || !StringTool.IsHex(readStr))
            {
                richTextBox_info.AppendText("Read Data Error\r\n");
                return;

            }
            string readLenStr = textBox_rLen1.Text;
            if (readLenStr.Trim().Equals(string.Empty) || !int.TryParse(readLenStr, out int iLength))
            {
                richTextBox_info.AppendText("Read Data Error\r\n");
                return;
            }
            byte[] readData = StringTool.StrToToHexByte(readStr);
            int rLen = int.Parse(readLenStr);
            byte[] readRs = i2c.ReadReg(readData, rLen);
            string[] readRsStr = Utils.DecToHex(readRs);
            string str = string.Format("Read Result: {0}\r\n", string.Join(" ", readRsStr));
            richTextBox_info.AppendText(str);

        }
        private void btn_read2_Click(object sender, EventArgs e)
        {
            string readStr = textBox_read2.Text;
            if (readStr.Trim().Equals(string.Empty) || !StringTool.IsHex(readStr))
            {
                richTextBox_info.AppendText("read data error\r\n");
                return;
            }
            string readLenStr = textBox_rLen2.Text;
            if (readLenStr.Trim().Equals(string.Empty) || !int.TryParse(readLenStr, out int iLength))
            {
                richTextBox_info.AppendText("read data error\r\n");
                return;
            }
            byte[] readData = StringTool.StrToToHexByte(readStr);
            int rLen = int.Parse(readLenStr);
            byte[] readRs = i2c.ReadReg(readData, rLen);
            string[] readRsStr = Utils.DecToHex(readRs);
            string str = string.Format("read result:{0}\r\n", string.Join(" ", readRsStr));
            richTextBox_info.AppendText(str);
        }

        private void btn_read3_Click(object sender, EventArgs e)
        {
            string readStr = textBox_read3.Text;
            if (readStr.Trim().Equals(string.Empty) || !StringTool.IsHex(readStr))
            {
                richTextBox_info.AppendText("read data error\r\n");
                return;
            }
            string readLenStr = textBox_rLen3.Text;
            if (readLenStr.Trim().Equals(string.Empty) || !int.TryParse(readLenStr, out int iLength))
            {
                richTextBox_info.AppendText("read data error\r\n");
                return;
            }
            byte[] readData = StringTool.StrToToHexByte(readStr);
            int rLen = int.Parse(readLenStr);
            byte[] readRs = i2c.ReadReg(readData, rLen);
            string[] readRsStr = Utils.DecToHex(readRs);
            string str = string.Format("read resullt:{0}", string.Join(" ", readRsStr));
            richTextBox_info.AppendText(str);
        }

        private void coef_textbox_TextChanged(object sender, EventArgs e)
        {

        }

        private static void SaveProcessedDataWithTime(List<short[]> processedData, List<DateTime> timeList, string filePath)
        {
            // 参数校验（确保数据和时间数量一致）
            if (processedData == null || timeList == null || processedData.Count != timeList.Count)
            {
                throw new ArgumentException("处理后的数据与时间列表数量不匹配");
            }
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("文件路径无效");
            }


            // 确保目录存在
            string directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // 写入文件
            using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {

                // 逐帧写入（时间与转换后的数据通过索引对应）
                for (int i = 0; i < processedData.Count; i++)
                {
                    //int index = i + 1; // 序号（从1开始）
                    DateTime time = timeList[i];
                    short[] data = processedData[i];

                    // 格式化时间（精确到毫秒）
                    string timeStr = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    // 格式化16位数据（逗号分隔）
                    string dataStr = string.Join("\t", data);

                    // 写入一行：时间,数据
                    writer.WriteLine($"[{timeStr}]\t{dataStr}");
                }
            }

        }

        //   1.2 拼接数据（低字节在前，高字节在后）
        private List<short[]> ProcessGroups(List<byte[]> results)
        {
            // 创建一个列表用于存储所有解析后的16位值
            List<short[]> allParsedValues = new List<short[]>();

            // 遍历每组数据
            for (int i = 0; i < results.Count; i++)
            {
                byte[] currentGroup = results[i];
                short[] data = new short[currentGroup.Length / 2];
                // 解析当前组数据为16位值
                for (int j = 0; j < currentGroup.Length; j += 2)
                {

                    short value = (short)((currentGroup[j + 1] << 8) | currentGroup[j]);
                    data[j / 2] = value;
                }
                allParsedValues.Add(data);
            }

            return allParsedValues;//.ToArray();
        }

        private byte[] ReadAdc()
        {
            byte[] wBuf = new byte[256];
            byte[] rBuf = new byte[256];
            wBuf[0] = I2CConstant.REG_IIC_ADDRESS;
            uint wLen = 0;
            uint rLen = 0;
            //1. EC W 00
            wBuf[1] = 0xEC;
            wBuf[2] = 0x00;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            //2. ED W 00
            wBuf[1] = 0xED;
            wBuf[2] = 0x00;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            //3. EC W 14
            wBuf[1] = 0xEC;
            wBuf[2] = 0x14;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            //4. ED R 1BYTE
            wBuf[1] = 0xED;
            wLen = 2;
            rLen = 1;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            int cnt = rBuf[0];
            //Console.WriteLine("rBuf = " + cnt);

            // RBUF[0] == 0?
            while (cnt == 0)
            {
                wBuf[1] = 0xED;
                wLen = 2;
                rLen = 1;
                IIC.WriteRead(wLen, wBuf, rLen, rBuf);
                cnt = rBuf[0];
                Utils.Sleep(3);
            }

            //5. EE R RBUF[0] BYTE
            wBuf[1] = 0xEE;
            wLen = 2;
            rLen = rBuf[0];
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            //  Console.WriteLine("rBuf = " +string.Join(",", rBuf));
            byte[] data = new byte[cnt];
            for (int i = 0; i < cnt; i++)
            {
                data[i] = rBuf[i];
            }

            //6. ED W 00
            wBuf[1] = 0xED;
            wBuf[2] = 0x00;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            //7. EC W 00
            wBuf[1] = 0xEC;
            wBuf[2] = 0x00;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            //8. ED W 00
            wBuf[1] = 0xED;
            wBuf[2] = 0x00;
            wLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);

            return data;
        }
        private byte[] ADC_uv()
        {
            byte[] wBuf = new byte[256];
            byte[] rBuf = new byte[256];
            wBuf[0] = I2CConstant.REG_IIC_ADDRESS;
            uint wLen = 0;
            uint rLen = 0;
            wBuf[1] = 0x1B;
            wLen = 2;
            rLen = 3;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            int cnt = 3;
            //   Console.WriteLine("rBuf = " + string.Join(",", rBuf));
            byte[] result_uv = new byte[cnt];
            for (int i = 0; i < cnt; i++)
            {
                result_uv[i] = rBuf[i];
            }
            return result_uv;
        }

        private void noise_textBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 1. 生成当前时间戳（年月日时分秒），作为文件夹名称
            string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            // 定义基础路径
            string baseDir = @"D:\Visual Studio Test\WindowsFormsApp1\Data";
            // 新建文件夹的完整路径
            string newFolderPath = Path.Combine(baseDir, timeStamp);

            //创建文件夹
            if (!Directory.Exists(newFolderPath))
            {
                Directory.CreateDirectory(newFolderPath);
                Console.WriteLine($"已创建新文件夹：{newFolderPath}");
            }


            //读取固件版本号
            fwVersion = i2c.ReadFwVersion();
            tvFwVersion.Text = fwVersion;
            Console.WriteLine("固件版本号：" + fwVersion);


            //读取校准系数
            byte[] data = ReadNum();
            string[] DecRsStr = Utils.DecToHex(data);
            string c = string.Join(",", DecRsStr);
            Console.WriteLine("DecRsStr=" + c);
            int dacToMv = data[1] << 8 | data[0];
            int dacToMv1 = data[3] << 8 | data[2];
            double coef = Math.Round(dacToMv / 1000.0, 3);
            double coef1 = Math.Round(dacToMv1 / 1000.0, 3);
            string coef_c = string.Join("", coef);
            coef_textbox.AppendText(coef_c);
            Console.WriteLine("校准系数：" + coef + coef1);


            //读取DAC转换系数
            byte[] data_Dac = ReadDac();
            int dataToDac = data_Dac[1] << 8 | data[0];
            double coef_Dac = Math.Round(dataToDac / 1000.0, 3);
            string dac_c = string.Join(",", coef_Dac);
            noise_textBox.AppendText(" DAC:" + dac_c + Environment.NewLine);
            Console.WriteLine("DAC_uv:" + dac_c);

            //读取offset
            byte[] data_Offset = ReadOFFSET();
            string[] offsetRsStr = Utils.DecToHex(data_Offset);
            int[] res_offset = HexDataProcessor.ProcessHexArray(offsetRsStr);
            //定义数组存储相乘结果
            double[] offsetResults = new double[res_offset.Length];
            //逐个元素相乘
            for (int i = 0; i < res_offset.Length; i++)
            {
                offsetResults[i] = res_offset[i] * coef_Dac;
            }
            string off = string.Join(",", offsetResults);
            noise_textBox.AppendText("offset:" + off + Environment.NewLine);
            Console.WriteLine("offset:" + off);

            // 判断offset结果，管控标准-220 ~ 220
            string offsetJudgeResult;

            // 假设初始状态为通过（pass）
            bool allInRange = true;

            // 遍历offsetResults数组，检查每个元素是否在[-220, 220]范围内
            foreach (double value in offsetResults)
            {
                // 如果有任何一个元素超出范围，标记为不通过
                if (value < -220 || value > 220)
                {
                    allInRange = false;
                    break; // 一旦发现不满足的元素，直接退出循环
                }
            }
            offsetJudgeResult = allInRange ? "pass" : "fail1";

            // 存放200帧adc数据
            // 1.获取200帧数据
            var rawDataList = new List<byte[]>(); // 存储原始字节数组（供ProcessGroups使用）
            var timeList = new List<DateTime>();  // 同步存储每帧数据的读取时间
                                                  // 读取200帧数据，同步记录原始数据和时间
            for (int i = 0; i < 200; i++)
            {

                DateTime readTime = DateTime.Now; // 记录当前读取时间
                byte[] data_Adc = ReadAdc();         // 获取原始字节数据
                rawDataList.Add(data_Adc);
                timeList.Add(readTime);
            }

            // 调用ProcessGroups方法处理数据
            List<short[]> processedData = ProcessGroups(rawDataList);

            // 绘制曲线
            DrawProcessedData(processedData, timeList);

            string adcTimeFilePath = Path.Combine(newFolderPath, "ADC_16位数据带时间.txt");
            SaveProcessedDataWithTime(processedData, timeList, adcTimeFilePath);
            Console.WriteLine($"ADC数据已保存至: {adcTimeFilePath}");

            //打印拼接后的值
            Console.WriteLine("processedData : [ " + string.Join(", ", processedData.Select(value =>
    "[" + string.Join(", ", value) + "]"
)) + " ]");

            //存储每组的差值结果
            List<short[]> differences = new List<short[]>();
            for (int i = 1; i < processedData.Count; i++)
            {
                short[] cur = processedData[i];
                short[] last = processedData[i - 1];
                short[] diff = new short[cur.Length];
                for (int j = 0; j < cur.Length; j++)
                {
                    // 计算对应元素的差值（当前元素 - 上一个元素）
                    diff[j] = (short)(cur[j] - last[j]);
                }

                differences.Add(diff);
            }

            Console.WriteLine("differences: [ " + string.Join(", ", differences.Select(diff =>
    "[" + string.Join(", ", diff) + "]"
)) + " ]");

            // 2. 读取adc_uv系数（静态0x1b）
            byte[] result_uv = ADC_uv();
            //  Console.WriteLine("result_uv="+string.Join(",", result_uv));
            double parse_uv = Math.Round((result_uv[2] << 16 | result_uv[1] << 8 | result_uv[0]) / 10000.0, 3);
            Console.WriteLine("parse_uv=" + string.Join(",", parse_uv));

            //noiseStd与noisepeak
            List<double> noiseStdList = new List<double>();

            long[] sumOfSquares = new long[2];
            long[] maxDiff = new long[2];
            foreach (short[] diffArray in differences)
            {

                for (int j = 0; j < 2; j++)
                {
                    sumOfSquares[j] += diffArray[j] * diffArray[j];
                    //maxDiff[j] = Math.Max(maxDiff[j], Math.Abs(diffArray[j]));
                    if (Math.Abs(diffArray[j]) > maxDiff[j])
                    {
                        maxDiff[j] = Math.Abs(diffArray[j]);
                    }
                }
            }

            double sum_std = sumOfSquares[0];
            double variance = sum_std / 199;
            double noiseStd = Math.Sqrt(variance) * parse_uv;
            double result_std = Math.Round(noiseStd, 3);

            double sum_std1 = sumOfSquares[1];
            double variance1 = sum_std1 / 199;
            double noiseStd1 = Math.Sqrt(variance1) * parse_uv;
            double result_std1 = Math.Round(noiseStd1, 3);

            double noisePeak = maxDiff[0] * parse_uv;
            double noisePeak1 = maxDiff[1] * parse_uv;

            Console.WriteLine(String.Join(",", sumOfSquares));
            Console.WriteLine(String.Join(",", maxDiff));

            // 判断noise结果，管控标准 std: 1~10, peak: 2~37
            // 定义判断结果变量
            string stdJudgeResult;
            bool isStdValid = (result_std >= 1 && result_std <= 10) && (result_std1 >= 1 && result_std1 <= 10);
            // 根据检查结果赋值
            stdJudgeResult = isStdValid ? "pass" : "fail";

            string speakJudgeResult;
            bool isSpeakValid = (noisePeak >= 2 && noisePeak <= 37) && (noisePeak1 >= 2 && noisePeak1 <= 37);
            speakJudgeResult = isSpeakValid ? "pass" : "fail";

            // 在主流程中调用保存方法
            //string allDataFilePath = @"D:\Visual Studio Test\WindowsFormsApp1\Data\所有设备数据.txt";
            //SaveAllDataToFile(allDataFilePath,fwVersion,coef, coef1,off, result_std, result_std1, noisePeak, noisePeak1);
            //Console.WriteLine($"所有数据已保存至: {allDataFilePath}");
            string allDataFilePath = Path.Combine(newFolderPath, "所有设备信息.txt");
            SaveAllDataToFile(allDataFilePath, fwVersion, coef, coef1, off, offsetJudgeResult, result_std, result_std1, stdJudgeResult, noisePeak, noisePeak1, speakJudgeResult);
            Console.WriteLine($"所有数据已保存至:{allDataFilePath}");
        }

        // 定义保存所有数据的方法
        private void SaveAllDataToFile(string filePath, string fwVersion, double coef, double coef1, string offset, string offsetJudgeResult, double result_std, double result_std1, string stdJudgeResult, double noisePeak, double noisePeak1, string speakJudgeResult)
        {
            // 创建字符串构建器高效拼接内容
            StringBuilder s = new StringBuilder();

            // 写入固件版本号
            s.AppendLine("设备信息");
            s.AppendLine($"固件版本号: {fwVersion}");
            s.AppendLine($"校准系数: [{coef},{coef1}]");
            s.AppendLine();

            // 写入Offset数据
            s.AppendLine("offset(单位：mv)");
            s.AppendLine("MIN:[-220.0,-220.0]");
            s.AppendLine("MAX:[220.0,220.0]");
            s.AppendLine($"Value:[ {offset}]");
            s.AppendLine($"Judge:[ {offsetJudgeResult}]");
            s.AppendLine();

            // 写入噪声标准差数据
            s.AppendLine("Noised_Std(单位：uv)");
            s.AppendLine("STD_MIN:[1.0,1.0]");
            s.AppendLine("STD_MAX:[10.0,10.0]");
            s.AppendLine($"VALUE:[ {result_std},{result_std1}]");
            s.AppendLine($"Judge:[ {stdJudgeResult}]");
            s.AppendLine();

            // 写入噪声峰值数据
            s.AppendLine("Noised_Speak(单位：uv)");
            s.AppendLine("PEAK_MIN:[2.0,2.0]");
            s.AppendLine("PEAK_MAX:[37.0,37.0]");
            s.AppendLine($"VALUE: [{noisePeak},{noisePeak1}]");
            s.AppendLine($"Judge:[ {speakJudgeResult}]");
            s.AppendLine();

            // 写入文件（确保目录存在）
            string directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            File.WriteAllText(filePath, s.ToString());
        }


        private byte[] ReadNum()
        {
            byte[] wBuf = new byte[256];
            byte[] rBuf = new byte[256];
            wBuf[0] = I2CConstant.REG_IIC_ADDRESS;
            uint wLen = 0;
            uint rLen = 0;
            wBuf[1] = 0x24;
            wLen = 2;
            rLen = 8;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            int cnt = 8;
            //   Console.WriteLine("rBuf = " + string.Join(",", rBuf));
            byte[] result_num = new byte[cnt];
            for (int i = 0; i < cnt; i++)
            {
                result_num[i] = rBuf[i];
            }
            return result_num;

        }

        private byte[] ReadDac()
        {
            byte[] wBuf = new byte[256];
            byte[] rBuf = new byte[256];
            wBuf[0] = I2CConstant.REG_IIC_ADDRESS;
            uint wLen = 0;
            uint rLen = 0;
            wBuf[1] = 0x1C;
            wLen = 2;
            rLen = 2;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            int cnt = 2;
            //   Console.WriteLine("rBuf = " + string.Join(",", rBuf));
            byte[] result_Dac = new byte[cnt];
            for (int i = 0; i < cnt; i++)
            {
                result_Dac[i] = rBuf[i];
            }
            return result_Dac;

        }

        private byte[] ReadOFFSET()
        {
            byte[] wBuf = new byte[256];
            byte[] rBuf = new byte[256];
            wBuf[0] = I2CConstant.REG_IIC_ADDRESS;
            uint wLen = 0;
            uint rLen = 0;
            wBuf[1] = 0x17;
            wLen = 2;
            rLen = 8;
            IIC.WriteRead(wLen, wBuf, rLen, rBuf);
            int cnt = 8;
            //   Console.WriteLine("rBuf = " + string.Join(",", rBuf));
            byte[] result_offset = new byte[cnt];
            for (int i = 0; i < cnt; i++)
            {
                result_offset[i] = rBuf[i];
            }
            return result_offset;
        }

        private void InitChart()
        {
            // 清除默认系列
            chart1.Series.Clear();

            //获取图表的默认图表区域（网格、坐标轴）
            ChartArea chartArea = chart1.ChartAreas[0];
            chartArea.AxisX.Title = "时间";       // X轴标题
            chartArea.AxisY.Title = "数值";       // Y轴标题
            chartArea.AxisX.MajorGrid.Enabled = true;  // 显示X轴网格
            chartArea.AxisY.MajorGrid.Enabled = true;  // 显示Y轴网格
            chartArea.AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Solid; // 网格线为实线
            chartArea.AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Solid;
            chartArea.AxisX.LabelStyle.Format = "HH:mm:ss"; // 时间格式
        }

     //   绘制处理后的数据曲线
        private void DrawProcessedData(List<short[]> processedData, List<DateTime> timeList)
        {


            // 清除现有曲线
            chart1.Series.Clear();

            // 获取通道数量
            int channelCount = processedData[0].Length - 1;

            // 定义曲线颜色
            Color[] colors = { Color.Blue, Color.Red, Color.Green };

            // 为每个通道创建曲线系列
            for (int channel = 0; channel < channelCount; channel++)
            {
                Series series = new Series($"通道{channel + 1}");
                series.ChartType = SeriesChartType.Line; // 曲线类型：折线图
                series.Color = colors[channel % colors.Length]; // 曲线颜色
                                                                
                series.BorderWidth = 2;//线宽
                
                chart1.Series.Add(series);
            }

            // 收集所有数据用于计算y轴范围
            List<short> allValues = new List<short>();
            foreach (var frame in processedData)
            {
                allValues.AddRange(frame);
            }
            //short minValue = allValues.Min();
            //short maxValue = allValues.Max();
            

            // 设置Y轴范围(留10%余量)
            //chart1.ChartAreas[0].AxisY.Minimum = minValue - (maxValue - minValue) * 0.1;
            //chart1.ChartAreas[0].AxisY.Maximum = maxValue + (maxValue - minValue) * 0.1;

            // 逐帧添加数据到曲线
            for (int frameIdx = 0; frameIdx < processedData.Count; frameIdx++)
            {
                DateTime time = timeList[frameIdx]; //当前帧时间
                short[] frameData = processedData[frameIdx]; //当前帧数据

                for (int channel = 0; channel < channelCount; channel++)
                {
                    // 向对应通道的曲线添加数据点
                    chart1.Series[$"通道{channel + 1}"].Points.AddXY(time, frameData[channel]);
                }
            }

            chart1.ChartAreas[0].RecalculateAxesScale();
        }

    }
}